import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:request_ruoyi/main.dart';

class Msg {
  static final GlobalKey<NavigatorState> _key = navigatorKey;

  static String _toStr<T>(T text) => text.toString();

  /* 轻提示（无 context） */
  static void toast<T>(T text, {int seconds = 2}) {
    final ctx = _key.currentContext;
    if (ctx == null) return;

    // Web/桌面用 SnackBar，真机用 Overlay
    if (!kIsWeb &&
        (Theme.of(ctx).platform == TargetPlatform.android ||
            Theme.of(ctx).platform == TargetPlatform.iOS)) {
      final overlay = Overlay.of(ctx, rootOverlay: true);
      final entry = OverlayEntry(
        builder: (_) => _ToastWidget(text: _toStr(text)),
      );
      overlay.insert(entry);
      entry.removeAfter(Duration(seconds: seconds));
    } else {
      ScaffoldMessenger.of(ctx).showSnackBar(
        SnackBar(
          content: Text(_toStr(text)),
          duration: Duration(seconds: seconds),
          behavior: SnackBarBehavior.floating,
        ),
      );
    }
  }

  /* SnackBar / AlertDialog 同理，只演示一个 */
  static void alert<T>(T text, {String? title}) {
    final ctx = _key.currentContext;
    if (ctx == null) return;
    showDialog(
      context: ctx,
      builder: (_) => AlertDialog(
        title: title == null ? null : Text(title),
        content: Text(_toStr(text)),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(ctx),
            child: const Text('知道了'),
          ),
        ],
      ),
    );
  }
}

/* ---------- 内部组件 ---------- */
class _ToastWidget extends StatelessWidget {
  final String text;
  const _ToastWidget({required this.text});

  @override
  Widget build(BuildContext context) {
    return Positioned(
      top: MediaQuery.of(context).size.height * 0.8,
      width: MediaQuery.of(context).size.width,
      child: Center(
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
          decoration: BoxDecoration(
            color: Colors.black87,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Text(
            text,
            style: const TextStyle(color: Colors.white, fontSize: 14),
          ),
        ),
      ),
    );
  }
}

extension _OverlayEntryExt on OverlayEntry {
  void removeAfter(Duration duration) => Future.delayed(duration, remove);
}
